package com.sc.test;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Shen Chao on 2018-03-17-017 上午 9:39.
 */

public class ZxingScanActivity extends AppCompatActivity {
    @BindView(R.id.dbv_scan)
    DecoratedBarcodeView dbvScan;
    @BindView(R.id.bt_light)
    Button btLight;
    private CaptureManager captureManager;//捕获管理器
    private boolean isLightOn = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zxing_scan);
        ButterKnife.bind(this);
        //没有闪光灯，就去掉按钮
        if (!hasFlash()) {
//            View.VISIBLE ===>设置控件可见
//            View.INVISIBLE===>设置控件不可见，但这个View仍然会占用布局
//            View.GONE===>设置控件不可见，但这个View在ViewGroup中不保留位置，会重新layout布局，不再占用空间
            btLight.setVisibility(View.GONE);
        }
        captureManager = new CaptureManager(this, dbvScan);
        captureManager.initializeFromIntent(getIntent(), savedInstanceState);
        captureManager.decode();
    }

    //判断是否有闪光灯
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    @Override
    protected void onPause() {
        super.onPause();
        captureManager.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        captureManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        captureManager.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return dbvScan.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        captureManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @OnClick(R.id.bt_light)
    public void onViewClicked() {
        if (isLightOn) {
            dbvScan.setTorchOff();
            isLightOn = false;
        } else {
            dbvScan.setTorchOn();
            isLightOn = true;
        }
    }

}
